from google.appengine.ext import webapp

from base_page import BaseHandler
from data import Pledge
from data import Request
from data import User

class CreatePledgeHandler(BaseHandler):
  # Set authenticating logic in the following two functions.
  def CanEdit(self, user, pledge):
    if not user:
      return False
    if user.is_sys_admin or user.is_donor_mod:
      return True
    if pledge == None:
      # TODO: everyone (with donor_profile) can add a new pledge
      return True
    if pledge.donor_profile.creator.key() == user.key():
      # One can always edit its own pledge
      return True
    else:
      return False

  def CanApprove(self, user, pledge):
    return user.is_sys_admin or user.is_donor_mod

  def ProcessGet(self):
    self.Setup('create_pledge.html', required_registered=True)
    pledge = self.GetEntityByKeyName('pid')
    # Check priviledges
    if self.CanEdit(self.user, pledge):
      self.template_values['can_edit'] = '1'
    else:
      # require at least editing priviledge to view this page
      self.RedirectLogin()
    if self.CanApprove(self.user, pledge):
      self.template_values['can_approve'] = '1'
    else:
      self.template_values['can_approve'] = '0'

    # list the user's donor_profiles
    profiles = list(self.user.donorprofile_set)
    if len(profiles) == 0:
      #TODO: alert this error
      self.RedirectAndRaise('/')
    self.template_values['profiles'] = profiles

    if pledge != None:  # edit an existing pledge
      self.template_values['pledge'] = pledge
      self.template_values['post_action'] = 'Action.edit'
    else:  # add a new pledge to a request
      request = self.GetEntityByKeyName('qid')
      if request == None:  # error
        self.RedirectAndRaise('/')
      self.template_values['req'] = request
      self.template_values['post_action'] = 'Action.add'
    # Done.
    self.Render()

  def ProcessPost(self):
    self.Setup('create_pledge.html')
    if self.post_action == 'Action.add':
      self.HandleAdd()
    elif self.post_action == 'Action.edit':
      self.HandleEdit()
    elif self.post_action == 'Action.delete':
      self.HandleDelete()
    elif self.post_action == 'Action.approve':
      self.HandleApprove()
    else:  # default handler
      self.JsonErrorReturn('Unknown action.')

  # Fill the pledge data from the form input
  def PopulatePledge(self, pledge):
    pledge.amount = int(self.request.get('amount'))
    pledge.description = self.request.get('description')
    pledge.donor_profile = self.GetEntityOrShowError('donor_profile')


  def HandleAdd(self):
    if not self.CanEdit(self.user, None):
      # TODO: more friendly alert
      self.RedirectLogin()
    request = self.GetEntityOrShowError('qid')
    pledge = Pledge()
    pledge.request = request
    pledge.state = Pledge.OPEN
    self.PopulatePledge(pledge)
    pledge.put()
    # redirect to view request page
    self.RedirectAndRaise('/viewrequest?qid=%s' % request.key())


  def HandleEdit(self):
    pledge = self.GetEntityByKeyName('pid')
    if pledge == None:
      # TODO: more friendly alert
      self.RedirectAndRaise('/')

    if not self.CanEdit(self.user, pledge):
      # TODO: more friendly alert
      self.RedirectLogin()

    self.PopulatePledge(pledge)
    pledge.put()
    self.RedirectAndRaise('viewrequest?qid=%s' % pledge.request.key())


  def HandleDelete(self):
    pledge = self.GetEntityByKeyName('pid')
    if pledge == None:
      # TODO: more friendly alert
      self.RedirectAndRaise('/')

    if not self.CanEdit(self.user, pledge):
      # TODO: more friendly alert
      self.RedirectLogin()
    # Save the request id before deleting
    qid = pledge.request.key()
    # TODO: update countings in related request
    pledge.delete()
    self.RedirectAndRaise('viewrequest?qid=%s' % qid)


  def HandleApprove(self):
    pledge = self.GetEntityByKeyName('pid')
    if pledge == None:
      self.JsonErrorReturn('Pledge does not exist.')

    # Authenticate
    if not self.CanApprove(self.user, pledge):
      self.JsonErrorReturn('Please login as admin or moderator.')

    new_state = self.GetFieldOrRedirect('state')
    pledge.state = int(new_state)
    pledge.put()

    repsonse = {}
    repsonse['status'] = 'OK'
    repsonse['state'] = new_state
    self.JsonReturn(repsonse)
